/*
 * 地址选择
 */
'use strict';
import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    Image,
    PixelRatio,
    Platform,
    TouchableOpacity,
    ScrollView,
    TextInput,
} from 'react-native';


import Toast from 'antd-mobile/lib/toast';
import List from 'antd-mobile/lib/list';
import InputItem from 'antd-mobile/lib/input-item';
import Button from 'antd-mobile/lib/button';
import TextareaItem from 'antd-mobile/lib/textarea-item';
import ActivityIndicator from 'antd-mobile/lib/activity-indicator';

import NavTitle from '../component/NavTitle';

var ImagePicker = require('react-native-image-picker');

import { createForm } from 'rc-form';

import XFetch from '../XFetch';

class AddGoods extends Component {
    constructor(props) {
        super(props)

        this.state = {
            files: [],
            animating:false,
            productImgs:[],
            logoImage:{uri:"httdds:www.baidu.com/1.png"},
            detaiImgs:[],
        }
    }

    componentDidMount(){
        if(this.props.id && this.props.id != 0){
            this._getInfo();
        }
    }

    _getInfo(){
        XFetch(`http://www.weiweigo.com/app/goods.aspx?method=showDetail&id=${this.props.id}`,{
            method:'GET',
        }).then(data=>{
            this.setState({
                logoImage: {
                    uri:`http://www.weiweigo.com${data.imgUrl}`
                },
                productImgs:data.focusimg?JSON.parse(data.focusimg).map(ele=>{
                    return {
                        uri:`http://www.weiweigo.com${ele.src}`
                    }
                }):[],
                detaiImgs:data.content_img?JSON.parse(data.content_img).map(ele=>{
                    return {
                        uri:`http://www.weiweigo.com${ele.src}`
                    }
                }):[],
            },()=>{
                this.props.form.setFieldsValue({
                    title:data.title,
                    content:data.content,
                    price:String(data.price)
                })
            })
        });
    }

    _uploadImg(img,obj,c) {
        let myHeaders = new Headers();
        myHeaders.append('Content-Type', 'multipart/form-data');

        let formData = new FormData();

        formData.append('imgFile', {uri: img.uri, name: img.fileName, type: 'image/jpeg'});
        formData.append('c', c);

        fetch(`http://www.weiweigo.com/app/member.aspx?method=upImg`,{
            method: 'POST',
            headers:myHeaders,
            body: formData,
        })
            .then(res => {
                res.json().then(data=>{
                    if(data.success){
                        if(Object.prototype.toString.call(obj) === '[object Array]'){
                            obj.push(data.val)
                        }else{
                            obj.imgUrl=data.val;
                        }
                    }else{
                        this.setState({
                            animating:false
                        });
                        clearInterval(this._timer);
                    }
                });
            })
    }

    _selectDetailImgs(){
        let options = {
            title: '',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'相册选择',
            mediaType:'photo',
            quality: 0.5
        };
        ImagePicker.showImagePicker(options, (response) => {
            let source = null;

            if(response.didCancel){
                return;
            }

            if(Platform.OS === 'ios') {
                // uri (on iOS)
                source = {uri: response.uri.replace('file://', ''), isStatic: true,fileName:response.fileName};
            } else {
                // uri (on android)
                source = {uri: response.uri, isStatic: true, fileName:response.fileName};
            }

            this.setState({
                detaiImgs: [...this.state.detaiImgs, source],
            })
        });
    }

    _selectLogo(){
        let options = {
            title: '',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'相册选择',
            mediaType:'photo',
            quality: 0.5
        };
        ImagePicker.showImagePicker(options, (response) => {
            let source = null;

            if(response.didCancel){
                return;
            }

            if(Platform.OS === 'ios') {
                // uri (on iOS)
                source = {uri: response.uri.replace('file://', ''), isStatic: true,fileName:response.fileName};
            } else {
                // uri (on android)
                source = {uri: response.uri, isStatic: true, fileName:response.fileName};
            }

            this.setState({
                logoImage:source
            })
        });
    }

    _renderDetailImgs(){
        return this.state.detaiImgs.map((ele, index) => {
            return(
                <TouchableOpacity
                    key = {index}
                    onPress={() => {

                    }}>
                    <Image style={[styles.showImage,{marginTop:5}]} source={ele}/>
                    <TouchableHighlight
                        style={styles.remove}
                        underlayColor='#c8c7cc'
                        onPress={() => this._removeDetailImg(index)}>
                        <Text style={{fontSize:10,color:'#fff'}}>X</Text>
                    </TouchableHighlight>
                </TouchableOpacity>
            );
        });
    }

    _removeDetailImg(index){
        this.state.detaiImgs.splice(index, 1);
        this.setState({
            detaiImgs:this.state.detaiImgs
        })
    }

    _removeImg(index) {
        this.state.productImgs.splice(index, 1);
        this.setState({
            productImgs:this.state.productImgs
        })
    }

    _selectProductImgs(){
        let options = {
            title: '',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'相册选择',
            mediaType:'photo',
            quality: 0.5
        };
        ImagePicker.showImagePicker(options, (response) => {
            let source = null;

            if(response.didCancel){
                return;
            }

            if(Platform.OS === 'ios') {
                // uri (on iOS)
                source = {uri: response.uri.replace('file://', ''), isStatic: true,fileName:response.fileName};
            } else {
                // uri (on android)
                source = {uri: response.uri, isStatic: true, fileName:response.fileName};
            }

            this.setState({
                productImgs: [...this.state.productImgs, source],
            })
        });
    }

    _renderImgs(){
        return this.state.productImgs.map((ele, index) => {
            return(
                <TouchableOpacity
                    key = {index}
                    onPress={() => this._showImage(index)}>
                    <Image style={[styles.showImage,{marginTop:5}]} source={ele}/>
                    <TouchableHighlight
                        style={styles.remove}
                        underlayColor='#c8c7cc'
                        onPress={() => this._removeImg(index)}>
                        <Text style={{fontSize:10,color:'#fff'}}>X</Text>
                    </TouchableHighlight>
                </TouchableOpacity>
            );
        });
    }

    _matchHttpImgs(url){
        return /^(http)/g.test(url);
    }

    _deleteBtn(){
        this.setState({
            animating:true
        });
        XFetch(`http://www.weiweigo.com/app/goods.aspx?method=del&id=${this.props.id}`,{
            method:'GET',
        }).then(data=>{
            if(data){
                Toast.success(data, 1);
                this.setState({
                    animating:false
                });
                this.props.navigator.popToTop();
            }
        });
    }

    _submitBtn(){
        this.props.form.validateFields((error, value) => {
            if(!error){
                this.setState({
                    animating:true
                });
                let focusimg = [],imgUrl = {},content_img=[];
                if(this._matchHttpImgs(this.state.logoImage.uri)){
                    imgUrl.imgUrl = this.state.logoImage.uri.replace('http://www.weiweigo.com','');
                }else{
                    this._uploadImg(this.state.logoImage,imgUrl,4);
                }

                for(let ele of this.state.productImgs){
                    if(this._matchHttpImgs(ele.uri)){
                        focusimg.push(ele.uri.replace('http://www.weiweigo.com',''))
                    }else{
                        this._uploadImg(ele,focusimg,3);
                    }
                }
                for(let ele of this.state.detaiImgs){
                    if(this._matchHttpImgs(ele.uri)){
                        content_img.push(ele.uri.replace('http://www.weiweigo.com',''))
                    }else{
                        this._uploadImg(ele,content_img,6);
                    }

                }
                this._timer = setInterval(function(){
                    if(imgUrl.imgUrl && focusimg.length === this.state.productImgs.length && this.state.detaiImgs.length === content_img.length){
                        clearInterval(this._timer);
                        if(this.props.id && this.props.id != 0){
                            value.id = this.props.id;
                        }
                        let _body = {
                            ...value,
                            imgUrl:imgUrl.imgUrl,
                            focusimg:JSON.stringify(focusimg.map(ele=>{
                                return {
                                    src:ele
                                }
                            })),
                            content_img:JSON.stringify(content_img.map(ele=>{
                                return {
                                    src:ele
                                }
                            }))
                        };


                        let formData = new FormData();

                        Object.keys(_body).map(ele=>{
                            formData.append(ele, _body[ele]);
                        });
                        XFetch(`http://www.weiweigo.com/app/goods.aspx?method=edit`,{
                            method:'POST',
                            headers:{
                                "Content-Type": "multipart/form-data"
                            },
                            body:formData
                        }).then(data=>{
                            if(data){
                                Toast.success(data, 1);
                                this.setState({
                                    animating:false
                                })
                                this.props.navigator.popToTop();
                            }
                        });
                    }
                }.bind(this),1000);

            }
        });
    }

    render() {
        const { getFieldProps } = this.props.form;
        return (
            <View style={styles.container}>
                <NavTitle
                    title='添加商品'
                    leftButton = {true}
                    leftImg = {require('../imgs/left.png')}
                    leftText = {'返回'}
                    leftHander = {()=>{this.props.navigator.pop()}}
                    headColor = '#fbdc3a'
                />
                <ScrollView
                    showsVerticalScrollIndicator={false}
                >
                <View style={styles.logoHead}>
                    <Image source={this.state.logoImage} style={styles.logoImg}/>
                    <TouchableOpacity style={styles.logoBtn} onPress={this._selectLogo.bind(this)}>
                        <Text style={styles.logoTxt}>选择头像</Text>
                    </TouchableOpacity>
                    <Text style={{marginLeft:10}}>300*300</Text>
                </View>
                <ScrollView contentContainerStyle={[styles.proHead]} showsHorizontalScrollIndicator={false}>
                    {
                        this._renderImgs()
                    }
                    <TouchableOpacity style={styles.proBtn} onPress={this._selectProductImgs.bind(this)}>
                        <Text style={[styles.proTxt,{fontSize:48,marginBottom:3}]}>+</Text>
                    </TouchableOpacity>
                    <Text style={{marginTop:10}}>640*300</Text>
                </ScrollView>
                <View style={styles.content}>
                    <InputItem
                        clear
                        placeholder="请输入商品名称"
                        {...getFieldProps('title',{
                            rules: [{required: true}],
                        })}
                        labelNumber={5}
                        maxLength = {20}
                    >商品名称</InputItem>
                    <InputItem
                        clear
                        placeholder="请输入价格"
                        type = 'number'
                        {...getFieldProps('price',{
                            rules: [{required: true}],
                        })}
                        labelNumber={5}
                    >价格</InputItem>
                    <List renderHeader={() => '商品介绍'}>
                        <TextareaItem
                            rows={3}
                            {...getFieldProps('summary',{
                                rules: [{required: true}],
                            })}
                            placeholder="商品介绍"
                        />
                    </List>
                </View>
                <View style={{flex:1,backgroundColor:"#FFF",marginTop:10}}>
                <ScrollView contentContainerStyle={[styles.proHead]} showsHorizontalScrollIndicator={false}>
                    {
                        this._renderDetailImgs()
                    }
                    <TouchableOpacity style={styles.detailBtn} onPress={this._selectDetailImgs.bind(this)}>
                        <Text style={[styles.proTxt,{fontSize:40}]}>+</Text>
                    </TouchableOpacity>
                </ScrollView>
                </View>
                <View style={styles.footer}>
                    {
                        this.props.id && this.props.id != 0?
                            <View style={styles.footerView}>
                                <Button onClick={this._deleteBtn.bind(this)}>删除</Button>
                            </View>
                        :null
                    }
                    <View style={[styles.footerView,{marginLeft:10}]}>
                        <Button style={styles.ensureBtn} onClick={this._submitBtn.bind(this)}>确定</Button>
                    </View>
                </View>
                </ScrollView>
                <ActivityIndicator
                    toast
                    text="数据更新"
                    animating={this.state.animating}
                />
            </View>
        )
    }

}
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#EEEEEF',
        flex: 1,
    },
    imageSelect:{
        paddingTop:10,
        paddingBottom:10
    },
    content:{
        backgroundColor:'#FFF'
    },
    footer:{
        flexDirection:'row',
        marginTop:30,
        justifyContent:'center',
        paddingLeft:20,
        paddingRight:20
    },
    footerView:{
        flex:1
    },
    proHead:{
        flexDirection:'column',
        alignItems:'center',
        padding:5,
        flex:1,
        backgroundColor:"#FFF",
        justifyContent:'center',
        marginBottom:10,
        marginTop:10
    },
    proBtn:{
        alignItems:'center',
        justifyContent:'center',
        borderWidth:1,
        padding:10,
        borderColor:'#D1D1D1',
        paddingLeft:25,
        paddingRight:25,
        marginTop:10
    },
    proTxt:{
        fontSize:13,
        color:'#666'
    },
    ensureBtn:{
        backgroundColor: '#fbdc3a',
        borderColor:'#fbdc3a',
    },
    showImage:{
        width:80,
        height:80
    },
    remove:{
        position: 'absolute',
        top: 3,
        right: -3,
        width: 16,
        height: 16,
        borderRadius: 8,
        backgroundColor: '#000',
        alignItems:'center',
        justifyContent:'center'
    },
    loginBtn:{
        padding:15,
        backgroundColor:'#FBDC3A',
        marginTop:20,
        borderRadius:3,
        justifyContent:'center',
        alignItems:'center'
    },
    logoHead:{
        flexDirection:'row',
        alignItems:'center',
        padding:5
    },
    logoImg:{
        width:80,
        height:80,
        marginRight:5
    },
    logoBtn:{
        borderWidth:1/PixelRatio.get(),
        borderRadius:3,
        borderColor:'#CCC',
        backgroundColor:'#FFF',
        padding:4,
        paddingLeft:5,
        paddingRight:5
    },
    logoTxt:{
        fontSize:13
    },
    detailBtn:{
        width:80,
        height:80,
        marginTop:10,
        borderWidth:1/PixelRatio.get(),
        borderRadius:3,
        borderColor:'#CCC',
        alignItems:'center',
        justifyContent:'center'
    },
});

export default createForm()(AddGoods);
